package dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;

import dao.AdvertisementDao;
import pojo.Advertisement;
import pojo.Food;
import pojo.Merchant;

@Repository
public class AdvertisementDaoImpl implements AdvertisementDao{

	@PersistenceContext(name="un")
	private EntityManager manager;
	
	@Override
	public Advertisement findById(String id) {
		String hq = "select a from Advertisement a where a.id=?";
		List<Advertisement> advertisements = manager.createQuery(hq).setParameter(1, id).getResultList();
		if (advertisements.size()>0) {
			return advertisements.get(0);
		}
    	return null;
	}

	
	@Override
	public List<Advertisement> findAll(String mId) {
		String hq = "select a from Advertisement a where a.merchant.id = ?";
    	List<Advertisement> list = (List<Advertisement>)manager.createQuery(hq).setParameter(1, mId).getResultList();
    	return list;
	}

	@Override
	public List<Advertisement> findByStatus(String mId,String status) {
		String hq = "select a from Advertisement a where a.merchant.id = ? and a.status = ?";
    	List<Advertisement> list = (List<Advertisement>)manager.createQuery(hq)
    			.setParameter(1, mId)
    			.setParameter(2, status)
    			.getResultList();
    	for(Advertisement a:list){
    		System.out.println("dao"+a.getStatus());
    	}
    	return list;
	}
	
	@Override
	public Advertisement update(String id, String status, String mId) {
		String hq = "select a from Advertisement a where a.id=? and a.merchant.id=?";
		List<Advertisement> advertisements = manager.createQuery(hq)
				.setParameter(1, id)
				.setParameter(2, mId)
				.getResultList();
		if (advertisements.size()>0) {
			Advertisement ad = advertisements.get(0);
			ad.setStatus(status);
			return ad;
		}
		return null;
		
	}

	@Override
	public Advertisement save(Advertisement ad, String mId) {
	System.out.println("dao"+ad.getFoodId());
		Food food = manager.find(Food.class, ad.getFoodId());
		Merchant merchant = manager.find(Merchant.class,mId);
		merchant.getAdvertisementList().add(ad);
		ad.setMerchant(merchant);
		ad.setFoodName(food.getName());
		ad.setFoodPrice(food.getPrice());
		ad.setImgPath(food.getImage());
		manager.persist(ad);
		return ad;
	}

}
